$(function(){
	//layui初始化，加载弹出层，表单等
	layui.use(['form', 'element','laydate','upload'], function(){
		layer = layui.layer;
		laydate = layui.laydate;
		element = layui.element;
		form = layui.form;
		upload = layui.upload;

		form.verify();

		$('.datetime').each(function(){
			laydate.render({elem: this, type: 'datetime', trigger: 'click'})
		})
		$('.date').each(function(){
			laydate.render({elem: this, type: 'date', trigger: 'click'})
		})

		form.on('switch(switch)',function(obj){
			var val = $(this).prop('checked');
			var url = $(this).attr('url');
			$.get(url, {val:val})
		})

		$('td').on('click', '.del', function(){
			var id = $(this).attr('data_id');
			var url = $(this).attr('url');
			layer.confirm('确认要删除吗？', function(index){
				$.get(url, {id: id, val: 'true'}, function(){
					$('.data_line[data_id=' + id + ']').remove();
					layer.closeAll();
				})
			});
		})

		$('.delAll').click(function(){
			var ids = tableCheck.getData();
			var url = $(this).attr('url');
			layer.confirm('确认要删除吗？', function(index){
				$.get(url, {id:ids,val:'true'},function(){
					$.each(ids,function(i,id){
						$('.data_line[data_id=' + id + ']').remove();
					})
					layer.closeAll();
				})
			})
		})

		form.on('submit(save)', function(data){
			formObj = $($(this).attr('form'));
			url = $('#form').attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				data: formObj.serialize(),
				dataType: "json",
				success: function(data){
					if(data.status == 1){
						layer.alert(data.message, function(){
							var index = parent.layer.getFrameIndex(window.name);
							parent.layer.close(index);
						});
					}else{
						layer.alert(data.message);
					}
				}
			});
			return false;
		})

		//单张图片上传
		upload.render({
			elem : '.uploadImage',
			url : '/ajax/Image/upImg',
			before : function(obj) {
				var i = this.item.index('.uploadImage');
				obj.preview(function(index, file, result) {
					$('.showImage:eq('+i+')').attr('src', result); //图片链接,上传后显示图片
				});
			},
			done : function(data) {
				if (data.code == 0) {
					var i = this.item.index('.uploadImage');
					$('.inpImage:eq('+i+')').val(data.data.src);
					layer.msg(data.msg);
				} else {
					layer.msg(data.msg);
				}
			}
		});

		upload.render({
			elem: '.uploadImages',
			url: '/ajax/Image/upImg',
			multiple: true,
			before: function(obj){
				var i = this.item.index('.uploadImages');
				obj.preview(function(index, file, result){
					$('.showImages:eq('+i+')').append('<div class="imgContainer uploadImageBoxes"><img src="'+result+'"><a href="javascript:;" class="uploadDels">删除</a></div>')
				});
			},
			done: function(data){
				if (data.code == 0) {
					var i = this.item.index('.uploadImages');
					var inpName = this.item.attr('inpName');
					$('.showImages:eq('+i+')').append('<input type="hidden" name="'+inpName+'[]" value="'+data.data.src+'" class="uploadInps"/>');
					layer.msg(data.msg);
				} else {
					layer.msg(data.msg);
				}
			}
		});

		$('body').on('click','.uploadDels',function(){
			var i = $(this).index('.uploadDels');
			$('.uploadImageBoxes:eq('+i+')').remove();
			$('.uploadInps:eq('+i+')').remove();
		})

		//初始化所属地
		$('[lay-filter=prov]').each(function(){
			var name = $(this).attr('name');
			$(this).html('<option value="">请选择省</option>');

			var target_city = $(this).attr('target_city');
			var target_county = $(this).attr('target_county');
			var prov_id = $(this).attr('prov_id');
			var city_id = $(this).attr('city_id');
			var county_id = $(this).attr('county_id');
			getArea(name,'0',prov_id);
			if(target_city!='' && target_city!=undefined && prov_id!='' && prov_id!=undefined) getArea(target_city,prov_id,city_id);
			if(target_county!='' && target_county!=undefined && city_id!='' && city_id!=undefined) getArea(target_county,city_id,county_id);
		})

		//获取地市信息
		function getArea(select_name, id, select_id){
			$.get(
				"/admin/common/area.html?id="+id
				,function(data){
					for(var i = 0; i < data.length; i++){
						var selected = select_id==data[i]['AreaId']?'selected':'';
						var option = '<option value="'+data[i]['AreaId']+'" '+selected+'>'+data[i]['AreaName']+'</option>';
						$("select[name="+select_name+"]").append(option);
					}
					form.render('select');
				}
			);
		}

		//绑定所在地事件
		form.on('select(prov)', function(data){
			var target_city = $(data.elem).attr('target_city');
			var target_county = $(data.elem).attr('target_county');
			if(target_city != ''){
				$("select[name=" + target_city + "]").html('<option value="">请选择市</option>');
				if(data.value) getArea(target_city, data.value);
			}
			if(target_county != ''){
				$("select[name=" + target_county + "]").html('<option value="">请选择县/区</option>');
			}
		});
		form.on('select(city)', function(data){
			var target_county = $(data.elem).attr('target_county');
			if(target_county != ''){
				$("select[name=" + target_county + "]").html('<option value="">请选择县/区</option>');
				if(data.value) getArea(target_county, data.value);
			}
		});
	});

	/*$('.area').each(function(){
		$(this).cxSelect({
			url: "/admin/common/area.html"
			, selects: ['province', 'city', 'county']
			, jsonName: 'AreaName'
			, jsonValue: 'AreaId'
			, emptyStyle: 'none'
		});
		form.render('select');
	})*/

	/*富文本编辑器*/
	$('.editor').each(function(){UE.getEditor($(this).attr('id'), {scaleEnabled: true});})

	/*列表页checkbox开始*/
	tableCheck = {
		init:function(){
			layui.use('form', function(){
				layui.form.on('checkbox(list_all)', function(obj){
					var checked = obj.elem.checked;
					$("[lay-filter=list_checkbox]").prop("checked", checked);
					layui.form.render('checkbox');
				})
			})
		},
		getData:function(){
			var arr = [];
			$("[lay-filter=list_checkbox]:checked").each(function(i,e){
				arr.push($(this).val());
			});
			return arr;
		}
	}

	//开启表格多选
	tableCheck.init();
	/*列表页checkbox结束*/

	//触发事件
	var tab = {
		tabAdd: function(title, url, id){
			//新增一个Tab项
			element.tabAdd('xbs_tab', {
				title: title
				, content: '<iframe tab-id="' + id + '" frameborder="0" src="' + url + '" scrolling="yes" class="x-iframe"></iframe>'
				, id: id
			})
		}
		, tabDelete: function(othis){
			//删除指定Tab项
			element.tabDelete('xbs_tab', '44'); //删除：“商品管理”
			othis.addClass('layui-btn-disabled');
		}
		, tabChange: function(id){
			//切换到指定Tab项
			element.tabChange('xbs_tab', id); //切换到：用户管理
		}
	};

	$('.container .left_open i').click(function(event){
		if($('.left-nav').css('left') == '0px'){
			$('.left-nav').animate({left: '-221px'}, 100);
			$('.page-content').animate({left: '0px'}, 100);
			$('.page-content-bg').hide();
		}else{
			$('.left-nav').animate({left: '0px'}, 100);
			$('.page-content').animate({left: '221px'}, 100);
			if($(window).width() < 768){
				$('.page-content-bg').show();
			}
		}
	});

	$('.page-content-bg').click(function(event){
		$('.left-nav').animate({left: '-221px'}, 100);
		$('.page-content').animate({left: '0px'}, 100);
		$(this).hide();
	});

	$('.layui-tab-close').click(function(event){
		$('.layui-tab-title li').eq(0).find('i').remove();
	});

	// 栏目多级显示效果
	var cateIds = [];

	function getCateId(cateId){
		$("tbody tr[fid=" + cateId + "]").each(function(index, el){
			id = $(el).attr('cate-id');
			cateIds.push(id);
			getCateId(id);
		});
	}
	$("tbody.x-cate tr[fid!='0']").hide();

	$('.x-show').click(function(){
		if($(this).attr('status') == 'true'){
			$(this).html('&#xe625;');
			$(this).attr('status', 'false');
			cateId = $(this).parents('tr').attr('cate-id');
			$("tbody tr[fid=" + cateId + "]").show();
		}else{
			cateIds = [];
			$(this).html('&#xe623;');
			$(this).attr('status', 'true');
			cateId = $(this).parents('tr').attr('cate-id');
			getCateId(cateId);
			for(var i in cateIds){
				$("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
			}
		}
	})

	//左侧菜单效果
	// $('#content').bind("click",function(event){
	$('.left-nav #nav li').click(function(event){
		if($(this).children('.sub-menu').length){
			if($(this).hasClass('open')){
				$(this).removeClass('open');
				$(this).find('.nav_right').html('&#xe697;');
				$(this).children('.sub-menu').stop().slideUp();
				$(this).siblings().children('.sub-menu').slideUp();
			}else{
				$(this).addClass('open');
				$(this).children('a').find('.nav_right').html('&#xe6a6;');
				$(this).children('.sub-menu').stop().slideDown();
				$(this).siblings().children('.sub-menu').stop().slideUp();
				$(this).siblings().find('.nav_right').html('&#xe697;');
				$(this).siblings().removeClass('open');
			}
		}else{
			var url = $(this).children('a').attr('_href');
			var title = $(this).find('cite').html();
			var index = $('.left-nav #nav li').index($(this));

			for(var i = 0; i < $('.x-iframe').length; i++){
				if($('.x-iframe').eq(i).attr('tab-id') == index + 1){
					tab.tabChange(index + 1);
					event.stopPropagation();
					return;
				}
			};
			tab.tabAdd(title, url, index + 1);
			tab.tabChange(index + 1);
		}
		event.stopPropagation();
	})
})

/*弹出层*/
function zhiju_show(title, url, w, h){
	if(title == null || title == '') title = false;
	if(url == null || url == '') url = "404.html";
	if(w == null || w == '' || $(window).width() < w) w = ($(window).width() * 0.9);
	if(h == null || h == '' || $(window).height() < h) h = ($(window).height() - 50);
	var index = layer.open({
		type: 2,
		area: [w + 'px', h + 'px'],
		fix: false, //不固定
		maxmin: false,
		shadeClose: true,
		shade: 0.4,
		title: title,
		content: url
	});
}